import { Injectable } from '@nestjs/common';
import { YixiantongFieldsGoodsService } from 'src/entities/yixiantong-fields-goods-service';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ReturnResult } from 'src/base/return-result';
import { RequestStatusCode, RequestStatusMessage } from 'src/constants';
import { YixiantongGoodsSerivcesOperateDto, YixiantongGoodsSerivcesSearchListDto } from './yixiantong-goods-services.dto';
import { YixiantongFieldsGoods } from 'src/entities/yixiantong-fields-goods';

@Injectable()
export class YixiantongGoodsServicesService {
  constructor(
    @InjectRepository(YixiantongFieldsGoodsService)
    private readonly yixiantongFieldsGoodsServiceRepository: Repository<YixiantongFieldsGoodsService>,
    @InjectRepository(YixiantongFieldsGoods)
    private readonly yixiantongFieldsGoodsRepository: Repository<YixiantongFieldsGoods>,
  ) {}

  async getList(searchParams: YixiantongGoodsSerivcesSearchListDto) {
    try {
      const keyword = searchParams.keyword ?? '';
      const page = searchParams.page ?? 1;
      const pageSize = searchParams.pageSize ?? 10;

      let queryBuilder = this.yixiantongFieldsGoodsServiceRepository.createQueryBuilder('service')
        .skip((page - 1) * pageSize)
        .take(pageSize > 1000 ? 1000 : pageSize)
        .where(`service.status = 1`);

      if (keyword?.length) {
        queryBuilder = queryBuilder
          .andWhere(`
          service.name LIKE :keyword
            OR service.field like :keyword
            OR service.address like :keyword
            OR service.cityName like :keyword
        `, { keyword: `%${keyword}%` })
      }
      const originList = await queryBuilder
        .select(['service.id', 'service.parking', 'service.wifi', 'service.createTime', 'service.updateTime'])
        .orderBy('service.updateTime', 'DESC')
        .getMany();

      const list = [];

      for (const item of originList) {
        const goodsItem = await this.yixiantongFieldsGoodsRepository.findOne({
          where: { id: item.id },
        })
        list.push({
          ...item,
          goodsItem,
        });
      }

      const total = (await this.yixiantongFieldsGoodsServiceRepository.findBy({ status: 1 })).length;
      return new ReturnResult(
        RequestStatusCode.Success,
        RequestStatusMessage.GetListSuccess,
        { list, total }
      );
    } catch (e) {
      return new ReturnResult(
        RequestStatusCode.OperateError,
        RequestStatusMessage.GetListError,
        null,
        e.message
      );
    }
  }

  async getListDetail(id: number) {
    try {
      const itemDetail = await this.yixiantongFieldsGoodsServiceRepository.findOne({
        where: { id, status: 1 },
        select: ['id', 'createTime', 'updateTime', 'parking', 'wifi'],
      });
      if (!itemDetail) {
        return new ReturnResult(
          RequestStatusCode.NotFound,
          RequestStatusMessage.GetDetailError,
          null,
          'Fail'
        );
      }
      const goodsItem = await this.yixiantongFieldsGoodsRepository.findOne({
        where: { id: itemDetail.id },

      });
      const data = {
        ...itemDetail,
        ...goodsItem,
      };
      return new ReturnResult(
        RequestStatusCode.Success,
        RequestStatusMessage.GetDetailSuccess,
        data
      );
    } catch (e) {
      return new ReturnResult(
        RequestStatusCode.NotFound,
        RequestStatusMessage.GetDetailError,
        null,
        'Fail'
      );
    }
  }

  async createOrUpdateListItem(formData: YixiantongGoodsSerivcesOperateDto) {
    try {
      const item = await this.yixiantongFieldsGoodsServiceRepository.findOne({
        where: { id: formData.id },
      });

      if (item) {
        // 如果已经存在，更新类目
        item.parking = formData.parking;
        item.wifi = formData.wifi;
        this.yixiantongFieldsGoodsServiceRepository.save(item);
        return new ReturnResult(
          RequestStatusCode.Success,
          RequestStatusMessage.UpdateSuccess,
          item
        );
      } else {
        // 如果不存在，创建类目
        const newItem = {
          ...formData,
          createTime: new Date(),
          updateTime: new Date(),
          status: 1,
        };
        await this.yixiantongFieldsGoodsServiceRepository.save(newItem);
        return new ReturnResult(
          RequestStatusCode.Success,
          RequestStatusMessage.CreateSuccess,
          newItem,
        );
      }
    } catch (e) {
      return new ReturnResult(
        RequestStatusCode.OperateError,
        `${RequestStatusMessage.CreateError}: ${e?.message}`,
        null,
        'Fail',
      );
    }
  }

  async deleteListItem(id: number) {
    try {
      const item = await this.yixiantongFieldsGoodsServiceRepository.findOne({
        where: { id },
      });
      if (!item) {
        return new ReturnResult(
          RequestStatusCode.NotFound,
          RequestStatusMessage.DeleteError,
          undefined,
          'Fail'
        );
      }
      item.status = 0;
      this.yixiantongFieldsGoodsServiceRepository.save(item);
      return new ReturnResult(
        RequestStatusCode.Success,
        RequestStatusMessage.DeleteSuccess,
        null,
      )
  } catch (e) {
      return new ReturnResult(
        RequestStatusCode.OperateError,
        RequestStatusMessage.DeleteError,
        null,
        'Fail'
      );
    }
  }
}
